import math
import logging
from odoo import api, fields, models, _, Command, SUPERUSER_ID
from odoo.exceptions import  ValidationError
_logger = logging.getLogger(__name__)


class SbOrderInternalChange(models.Model):
    _inherit = 'sb.order.internal.change'

    s_mes_lock = fields.Boolean(string='已同步MES', help='同步mes的工单不允许在odoo过数', default=False, copy=False)

    def _sb_init_record(self):
        records=  self.search([('state', '=', 'done')])
        records.write({'s_mes_lock': True})

    # =========CSA没有签发 先关闭接口20251117========
    def btn_confirm(self):
        res = super().btn_confirm()
        # if not self.target_product.s_mes_lock:
        #     self.target_product.is_allow_to_mes = True
        #     self.target_product.product_tmpl_id.post_mes_async()
        # self.action_mes_production()
        return res

    def _cron_mes_production(self):
        change_ids = self.sudo().search([('s_mes_lock', '=', False), ('state', '=', 'done')])
        for change in change_ids:
            change.action_mes_production()

    def _get_all_productions(self, production):
        children_ids = production  # 全部内层MO
        visited = [production]
        production = visited[0]
        while visited and visited.pop(0):
            children_ids |= production._get_children()
            visited.extend([p for p in production._get_children()])
            if visited:
                production = visited[0]
        return children_ids

    def action_mes_production(self):
        production_ids = self.work_productions.filtered(lambda x: x.to_change).mapped('production_id')
        all_production_ids = production_ids
        for production in production_ids:
            all_production_ids |= self._get_all_productions(production)
        data_vals = [{
            'prod_code': self.target_product.default_code,
            'version': self.target_product.versions,
            'remark': self.remarks if self.remarks else '',
            'mo_list': [{'mo_code': p.name} for p in all_production_ids if p.state not in ['done', 'cancel']]
        }]
        data = {
            "docType": "API_MO_EDIT",
            "updateType": "UPDATE",
            "data": data_vals
        }
        result = self.env['s.mes.upload'].upload_data(data)
        if result and result.get('resultCode') == '0000':
            self.s_mes_lock = True
        else:
            self.env.cr.rollback()
            raise ValidationError(f'同步MES失败：{str(result)}')
